#include "dttestdata.h"

#include <QDebug>

#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif

DtTestData::DtTestData(QObject *parent) :
    QObject(parent)
{
}

DtTestData::~DtTestData()
{
}

void DtTestData::ProcessingDatas(char *data, int count)
{
    qDebug() << QString::fromUtf8("Plugin(%1), func(%2)").arg(QStringLiteral(DtTestData_iid)).arg(QStringLiteral(Q_FUNC_INFO));

    frame_list_.clear();

    int begin = 0, end = 0;
    for (int i = 0; i <= count - 2; ++i) {
        if (data[i] != '\r' && data[i+1] != '\n') {
            continue;
        }
        end = i + 1; // 已找到帧尾 <CR><LF>

        bool frame_is_valid = false;
        char *frame_head_ptr = data + begin;
        int frame_count = i - begin + 2;
        int image_size = 0;
        Frame frame;

        QString frame_str = QString::fromLocal8Bit(frame_head_ptr, frame_count);
        if ( frame_str.startsWith(QStringLiteral("$GCCMD,TEST DATA,")) && frame_str.contains(QChar::fromLatin1('*')) && frame_str.count(QChar::fromLatin1('*')) == 1 ) {
            QString data_with_end_str = frame_str.remove(QStringLiteral("$GCCMD,TEST DATA,"));
            int data_end_index = data_with_end_str.indexOf(QChar::fromLatin1('*'));
            if (data_end_index >= 21 && data_with_end_str.count(QChar::fromLatin1(',')) == 21 ) {
                QString data_str = data_with_end_str.left(data_end_index);
                qDebug() << QString::fromUtf8("Plugin(%1), Data(%2)").arg(QStringLiteral(DtTestData_iid)).arg(data_str);
                QList<QString> data_strlist = data_str.split(QChar::fromLatin1(','), QString::KeepEmptyParts);
                for (int i = 0; i < data_strlist.length(); ++i) {
                    float value = data_strlist[i].trimmed().toFloat();
                    frame.datas_.append(value);
                }
                frame_is_valid = true;
            }
        }

        // 记录帧
        frame.is_valid_ = frame_is_valid; // 帧数据是否合法
        frame.start_index_ = begin; // 开始位置
        frame.end_index_ = end; // 结束位置
        frame.image_size_ = image_size; // 图片数据大小, 0则表示为非图片数据
        frame_list_.append(frame); // 添加到帧数据链表中

        begin = i + 2;
    }
}
